from mcp import StdioServerParameters, ClientSession, stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
import asyncio
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
from pydantic import SecretStr

# 创建模型实例（远程调用）
llm = ChatOpenAI(
    model_name="qwen3-max",
    temperature=0,
    openai_api_key=SecretStr("sk-f4fb03bbc29b4f0995b60dec52645af0"),
    openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",
    streaming=True,
)

async def create_mcp_playerwright_client():
    server_params = StdioServerParameters(
        command="npx",
        args=["@playwright/mcp@latest"]
    )

    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            tools = await load_mcp_tools(session)
            print(tools)
            
            agent = create_react_agent(
                model=llm,
                tools=tools,
                debug=True
            )

            response = await agent.ainvoke(input={"message":[("user", "在浏览器中使用网站www.baidu.com查询北京的天气")]})

            print(response)

asyncio.run(create_mcp_playerwright_client())